<?php

include_once 'autoload.php';

class FormLogin extends Zend_Form {

    public function init() {
        $this->setName('Login');
        
        $id = new Zend_Form_Element_Text('id');
        $id->setLabel('Identifiant')
                ;
        $userName = new Zend_Form_Element_Text('userName');
        $userName->setLabel('Nom: ')
                ->setRequired();


        $pwdValide = new Zend_Validate_Regex('((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})');
        $pwdValide->setMessage("6 a 20 caracteres, au moins 1 chiffre, au moins une majuscule");

        $password = new Zend_Form_Element_Password('userPwd');
        $password->setLabel('Mot de passe:')
                ->setRequired()
                ->addValidator($pwdValide);
        $login = new Zend_Form_Element_Submit('login');
        $login->setLabel('Envoyer');
        $this->addElements(array($id,$userName, $password, $login))
                ->setMethod('post')
                ->setAction('formAuth01.php');
    }

}

function estAuthentifie($userName, $userPwd) {

    $db = new Zend_Db_Adapter_Pdo_Mysql(array(
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname' => 'gsb_frais'
    ));
    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
    $authAdapter->setTableName('comptable')
            ->setIdentityColumn('login')
            ->setCredentialColumn('mdp');
    $authAdapter->setIdentity($userName)
            ->setCredential($userPwd);


    $auth = Zend_Auth::getInstance();
    $result = $auth->authenticate($authAdapter);
    return ($result->isValid() ? TRUE : FALSE);
}

$view = new Zend_View(); //autoload 
$form = new FormLogin(); //autoload 
if (!$_POST) {
// rendu du formulaire vierge 
    echo $form->render($view);
} else
if (!$form->isValid($_POST)) {
// rendu du formulaire rempli et messages d'erreurs 
    echo $form->render($view);
} else {
    $userName = $form->getValue('userName');
    $userPwd = $form->getValue('userPwd');
    if (!estAuthentifie($userName, $userPwd)) {
        echo $form->render($view);
        echo " Authentification failed";
    } else {
        echo "Authentification reussie";
    }
// formulaire valide.traiter les donnees postees 
    //Zend_Debug::dump($_POST); idem var_dump($_POST) 
    //Zend_Debug::dump($form->getValues());
}
?>
